const jwt = require('jsonwebtoken')
const fs = require('fs')

module.exports = class extends think.Service {
  /**
   * 构造函数
   * @param publicKey 公钥文件
   * @param privateKey 私钥文件
   */
  constructor (...args) {
    super(...args)
    const certPath = `${think.ROOT_PATH}/src/common/service/cert/jwt`
    this.publicKey = fs.readFileSync(`${certPath}/public.pem`, 'utf-8')
    this.privateKey = fs.readFileSync(`${certPath}/private.pem`, 'utf-8')
  }

  /**
   * jwt加密
   * @param data 要加密的数据
   * @param expiresIn 过期时间(单位：秒) 默认7天
   */
  async encrypt (data, expiresIn = 604800) {
    const encrypt = await jwt.sign(data || {}, this.privateKey, { algorithm: 'RS256', expiresIn })
    return encrypt
  }

  /**
   * jwt解密
   * @param data 待解密数据
   */
  async decrypt (data) {
    if (think.isEmpty(data)) {
      yy.log.error('token is empty')
      return null
    }
    try {
      const json = await jwt.verify(data, this.publicKey)
      delete json.iat
      delete json.exp
      return json
    } catch (e) {
      yy.log.error(`token decrypt error, token: ${data}`, e)
      return null
    }
  }
}
